<template>
  <view
    id="recordButton"
    w-670rpx
    h-100rpx
    rounded-20rpx
    relative
    flex
    items-center
    justify-center
    px-40rpx
    box-border
    ml-40rpx
    mt-14rpx
    bg="#fff"
    text-28rpx
    font-bold
    @touchstart="startRecording"
    @touchmove="checkCancel"
    @touchend="stopRecording"
    @touchcancel="touchcancelVoice"
    style="box-shadow: 0rpx 2rpx 8rpx 0rpx rgba(168, 109, 0, 0.25); letter-spacing: 2px">
    {{ voiceText }}
    <image
      w-40rpx
      h-50rpx
      absolute
      right-40rpx
      src="@/pages/funcPages/static/aiChat/keyboard.png"
      @touchstart.stop="emit('changeInput')"></image>
  </view>
  <!-- 音幅显示 -->
  <view v-if="isRecording" class="recording-overlay" :style="{ display: isRecording ? 'flex' : 'none' }">
    <view class="recording-animation">
      <view class="wave-container">
        <view class="wave-bar" v-for="n in 5" :key="n"></view>
      </view>
      <view>{{ cancelRecording ? '松开取消' : '松开结束' }}</view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
// import storage from '@/utils/storage'
// import api from '@/config/api'
const props = defineProps({
  authorization: {
    type: String,
    default: () => ''
  },
  aiAnswerComplete: { // 回答完成
    type: Boolean,
    default: () => false
  }
})

// let accessToken = storage.getAccessToken()
// const accountInfo = uni.getAccountInfoSync()
// const innerAudioContext = uni.createInnerAudioContext() //音频
const emit = defineEmits(['changeInput', 'sendVoice', 'sendVoiceSuccess', 'sendVoiceError'])
// import { sendChatMessage } from "../utils/utils";
const isRecording = ref(false) // 是否正在录音
const cancelRecording = ref(false) // 是否取消发送
const authorization = computed(() => {
  return props.authorization || ''
})
// const volume = ref(0) // 实时音量

const voiceTimer = ref<any>(null) // 录音时长
const voiceLength = ref(0) // 录音时长
const voicePageY = ref(0) // 按钮位置

// 计算属性, 计算按钮文字显示
const voiceText = computed(() => {
  if (isRecording.value) {
    return cancelRecording.value ? '松开取消' : '松开结束'
  } else {
    return '按住说话'
  }
})

let recorderManager: any = null // 录音管理器

// 开始录音
const startRecording = (event: any) => {
  if (!props.aiAnswerComplete) { // 回答完成, 不允许录音
    uni.showToast({ title: '请等待AI回答完毕', icon: 'none' })
    return
  }
  voicePageY.value = event.changedTouches[0].pageY.toFixed(2)
  cancelRecording.value = false
  isRecording.value = true
  voiceLength.value = 0
  console.log('开始录音')
  // 开始录音
  recorderManager.start({
    format: 'wav'
  })
  voiceTimer.value = setInterval(() => {
    voiceLength.value += 0.1
  }, 100)
}

// 检测是否取消发送
const checkCancel = (event: any) => {
  let numTemp = voicePageY.value - event.changedTouches[0].pageY.toFixed(2)
  cancelRecording.value = numTemp >= 60
}
// 停止录音
const stopRecording = () => {
  if (isRecording.value) {
    isRecording.value = false
    recorderManager.stop()
    console.log('停止录音')
  }
}

const touchcancelVoice = () => {
  if (isRecording.value) {
    isRecording.value = false
    cancelRecording.value = true
    recorderManager.stop()
    console.log('取消录音')
    // volume.value = 0 // 重置音量
  }
}

// 发送录音文件
const sendRecording = (filePath: string) => {
  emit('sendVoice', '')
  uni.uploadFile({
    url: 'https://api.coze.cn/v1/audio/transcriptions',
    filePath: filePath,
    name: 'file',
    header: {
      Authorization: `Bearer ${authorization.value}`,
      'Content-Type': 'multipart/form-data'
    },
    success: (res: any) => {
      console.log('上传成功', res)
      if (res.statusCode === 200) {
        const data = JSON.parse(res.data)
        if (data.code == 0) {
          emit('sendVoiceSuccess', data.data.text)
        } else {
          emit('sendVoiceError')
        }
      } else {
        emit('sendVoiceError')
      }
    },
    fail: (err) => {
      console.error('上传失败', err)
      emit('sendVoiceError')
    }
  })
}

// const playVoice = (filePath: string) => {
//   const innerAudioContext = uni.createInnerAudioContext()
//   innerAudioContext.src = filePath
//   innerAudioContext.play()
//   innerAudioContext.onStop(() => {
//     innerAudioContext.destroy()
//   })
// }

onMounted(() => {
  uni.authorize({
    scope: 'scope.record',
    success() {
      recorderManager = uni.getRecorderManager()

      recorderManager.onStop((res: any) => {
        console.log('定时器:' + voiceTimer.value, '录音时长:' + voiceLength.value)
        console.log('onStop录音文件：', res)
        if (voiceTimer.value) {
          console.log('清除定时器')
          clearInterval(voiceTimer.value)
          voiceTimer.value = null
        }
        if (voiceLength.value < 1) {
          uni.showToast({
            icon: 'error',
            title: '说话时间太短'
          })

          return
        }
        voiceLength.value = 0

        if (!cancelRecording.value) {
          sendRecording(res.tempFilePath)
        }
      })
      recorderManager.onError((res: any) => {
        console.error('录音错误', res)
      })
    },
    fail() {
      console.error('未授权录音')
    }
  })
})
</script>

<style lang="scss" scoped>
.recording-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  // background-color: rgba(0, 0, 0, 0.5);
  display: none;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.recording-animation {
  background-color: rgba(0, 0, 0, 0.5);
  border-radius: 16px;
  padding: 30px;
  width: 150px;
  text-align: center;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  color: #fff;
}

.mic-icon {
  width: 60px;
  height: 60px;
  margin: 0 auto 20px;
  color: #ff4d4f;
}

.mic-icon svg {
  width: 100%;
  height: 100%;
}

.wave-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 40px;
  margin-bottom: 20px;
}

.wave-bar {
  width: 6px;
  height: 20px;
  margin: 0 3px;
  background-color: #fff;
  border-radius: 3px;
  animation: wave 1.2s ease-in-out infinite;
}

.wave-bar:nth-child(1) {
  animation-delay: 0.1s;
}
.wave-bar:nth-child(2) {
  animation-delay: 0.2s;
}
.wave-bar:nth-child(3) {
  animation-delay: 0.3s;
}
.wave-bar:nth-child(4) {
  animation-delay: 0.4s;
}
.wave-bar:nth-child(5) {
  animation-delay: 0.5s;
}

@keyframes wave {
  0%,
  100% {
    transform: scaleY(0.8);
  }
  50% {
    transform: scaleY(1.8);
  }
}
</style>
